<template>
  <div class="form-section">
    <!-- <div class="section-header">
      <h3 class="section-title">
        {{ submission?.isDraft ? '编辑作业' : '提交作业' }}
      </h3>
    </div> -->
    <div class="section-content">
      <!-- 过期或终止提示 -->
      <div v-if="isOverdue || isTerminated" class="mb-6">
        <!-- 过期提示 -->
        <el-alert
          v-if="isOverdue"
          title="作业已过期"
          type="error"
          :closable="false"
          show-icon
        >
          <template #default>
            <p class="mb-2">
              <strong>截止时间：</strong>{{ formatDate(assignment?.dueDate) }}
            </p>
            <p class="text-sm">作业提交时间已过，无法再提交作业或保存草稿</p>
          </template>
        </el-alert>

        <!-- 终止提示 -->
        <el-alert
          v-else-if="isTerminated"
          title="作业已终止"
          type="error"
          :closable="false"
          show-icon
        >
          <template #default>
            <p class="mb-2" v-if="assignment?.terminatedReason">
              <strong>终止原因：</strong>{{ assignment.terminatedReason }}
            </p>
            <p class="text-sm">该作业已被教师终止，无法再提交作业或保存草稿</p>
          </template>
        </el-alert>
      </div>

      <!-- 表单内容 -->
      <div v-if="!isOverdue && !isTerminated">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          size="large"
          scroll-to-error
        >
          <!-- 作业内容 -->
          <el-form-item label="作业内容" prop="content" required>
            <div class="w-full">
              <wang-editor
                ref="editorRef"
                v-model="form.content"
                :height="'350px'"
                :placeholder="'请在此输入您的作业内容...'"
                :max-length="5000"
              />
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 只读显示（过期或终止时显示现有内容） -->
      <div v-else-if="submission?.content" class="mt-4">
        <h4 class="text-base font-medium text-gray-900 mb-3">当前作业内容</h4>
        <div
          class="prose max-w-none text-gray-700 p-4 bg-gray-50 rounded-lg border"
          v-html="submission.content"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import type { Submission } from "../../../../api/submissions";
import { useSubmissionUtils } from "../composables";

interface Props {
  submission?: Submission | null;
  assignment?: any;
  isOverdue?: boolean;
}

const props = defineProps<Props>();

const { formatDate } = useSubmissionUtils();

const formRef = ref();
const editorRef = ref();

// 计算属性
const isTerminated = computed(() => {
  return props.assignment?.status === "terminated";
});

// 表单数据
const form = reactive({
  content: "",
});

// 自定义校验函数：检查富文本的实际字符长度
const validateContent = (rule: any, value: string, callback: any) => {
  // 获取富文本编辑器的实际字符长度
  const textLength = editorRef.value?.getTextLength() || 0;

  console.log("🔍 校验富文本内容:", {
    htmlValue: value,
    htmlLength: value?.length || 0,
    textLength: textLength,
    editorRef: !!editorRef.value,
  });

  if (textLength === 0) {
    callback(new Error("请输入作业内容"));
    return;
  }

  if (textLength < 10) {
    callback(
      new Error(`作业内容至少需要10个字符，当前只有${textLength}个字符`)
    );
    return;
  }

  callback();
};

// 校验规则
const rules = {
  content: [
    {
      required: true,
      validator: validateContent,
      trigger: "blur",
    },
  ],
};

// 校验方法
const validate = async () => {
  try {
    await formRef.value?.validate();
    return true;
  } catch (error) {
    return false;
  }
};

// 暴露表单实例和数据给父组件
defineExpose({
  formRef,
  form,
  validate,
});

// 监听 submission 变化，填充表单数据
watch(
  () => props.submission,
  (newSubmission) => {
    if (newSubmission) {
      form.content = newSubmission.content || "";
    }
  },
  { immediate: true }
);

defineOptions({
  name: "SubmissionForm",
});
</script>

<style scoped>
/* 表单分区样式 */
.form-section {
  border-bottom: 1px solid #f0f2f5;
}

.section-header {
  padding: 20px 24px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e5e7eb;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  margin-right: 12px;
  border-radius: 2px;
}

.section-content {
  /* padding: 24px; */
}
</style>
